import React, {Component} from 'react';
import EventHandler from "../../rx/EventHandler";
import BookManagerActions from "./actions/BookManagerActions";

const ENTER_KEY = 13;

class Header extends Component {
  componentWillMount() {
    let newFieldKeyDown = EventHandler();
    let enterEvent = newFieldKeyDown.filter(function (event) {
      return event.keyCode === ENTER_KEY;
    });

    enterEvent.forEach(function (event) {
      console.log("you enter");
      event.stopPropagation();
      event.preventDefault();
    });

    enterEvent
      .map(function (event) {
        return event.target.value.trim();
      })
      .filter(function (value) {
        return !!value;
      }).subscribe(BookManagerActions.create);

    enterEvent
      .forEach(function (event) {
        event.target.value = '';
      });


    this.handlers = {
      newFieldKeyDown: newFieldKeyDown
    };
  }

  render() {
    return (
      <header id="header">
        <h1>todos</h1>
        <input
          id="new-todo"
          placeholder="W needs to be done?"
          autoFocus={true}
          onKeyDown={this.handlers.newFieldKeyDown}
        />
      </header>
    );
  }
}

export default Header;
